package httpLogRequests;
import java.util.ArrayList;


public class User {

	/** Max time (milliseconds) between two request to consider them to be in the same session*/
	static private int MAX_MS_BETWEEN_REQUEST = 30 * 60 * 1000;					
	
	private ArrayList<Session> userSessions;			/** List of request made by one user */
	/**
	 * Number of sessions created for this user
	 */
	private int numberSessions;
	
	//TODO Maybe add an ID for each user?
	/**
	 * 
	 */
	private String userIP;
	
	/**
	 * Builder
	 */
	public User(String userIP) {
		this.userSessions = new ArrayList<Session>();
		numberSessions = 0;
		this.userIP = userIP;
	}
	
	/**
	 * Adding a request to one session, according to its timestamp regarding ending of other sessions
	 * @param req
	 * 		The request to add
	 */
	public void putNewRequest(Request req) { 
		
		for (Session session : this.userSessions) {
			if (req.getTimeStamp().getTime() - session.getLastTimeStamp() < User.MAX_MS_BETWEEN_REQUEST ) {
				session.addRequest(req);
				return;
			}
		}
		
		// If we haven't found any suitable session, we start a new one
		Session newSession = new Session();
		newSession.addRequest(req);
		this.userSessions.add(newSession);
		numberSessions++;
		
	}
	/**
	 * To get the number of the sessions made by this user
	 * @return
	 */
	public int getNumberSessions(){return numberSessions;}
	/**
	 * To get the IP-adress of this user
	 * @return
	 */
	public String getUserIP(){return this.userIP;}
	/**
	 * To get all the sessions from this user
	 * @return a list of the user's sessions
	 */
	public ArrayList<Session> getUserSessions() { return this.userSessions;}
	
	/**
	 * To get the average length from all the sessions of the user
	 * @return: the average sessions' length for this user
	 */
	public double getSessionsAverageLength(){
		int totalLength = 0;
		for(Session session: userSessions){
			totalLength += session.getNRequest();
		}
		return totalLength/userSessions.size();
	}
	
}
